package cc.dawning.utiming.lklocation.location.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.chad.library.adapter.base.BaseQuickAdapter;
import cc.dawning.utiming.lklocation.R;
import cc.dawning.utiming.lklocation.location.activity.LocationSourceActivity;
import cc.dawning.utiming.lklocation.location.adapter.LocationSearchAdapter;
import cc.dawning.utiming.lklocation.location.global.LocationHandlerKey;
import cc.dawning.utiming.lklocation.location.utils.LocationSearchDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Date 2018/3/28
 * Describe 搜索弹窗
 *
 * @auther liuxin
 */

public class SearchDialog {
    /**
     * 搜索框实例对象
     */
    private static SearchDialog mInstance;
    /**
     * 弱引用当前activity对象
     */
    private LocationSourceActivity mActivity;
    /**
     * 搜索输入框
     */
    private EditText et_dialog_search;
    /**
     * 清除输入按钮
     */
    private ImageView iv_dialog_del;
    /**
     * 取消按钮
     */
    private TextView tv_dialog_cancle;

    /**
     * 无结果展示
     */
    private View view_search_bg;

    /**
     * 搜索结果展示layout
     */
    private LinearLayout ll_search_result;

    /**
     * 搜索结果展示列表
     */
    private RecyclerView rv_search_result;

    /**
     * 搜索dialog
     */
    private Dialog dialog;
    /**
     * 保存activity的searchView
     */
    private ViewGroup searchView;
    /**
     * 搜索监听
     */
    private MyInputQueryListener myInputQueryListener;
    /**
     * 初始数据源
     */
    private ArrayList<Tip> dataList = new ArrayList<>();
    /**
     * 列表展示适配器
     */
    private LocationSearchAdapter searchAdapter;

    /**
     * 单例模式获取实例
     */
    public static SearchDialog getInstance() {
        if (null == mInstance) {
            synchronized (SearchDialog.class) {
                if (null == mInstance) {
                    mInstance = new SearchDialog();
                }
            }
        }
        return mInstance;
    }

    /**
     * 搜索监听
     */
    private class MyInputQueryListener implements Inputtips.InputtipsListener {

        @Override
        public void onGetInputtips(List<Tip> list, int i) {
            mActivity.hideLoadView();
            dataList.clear();
            dataList.addAll(list);
            if (null != searchAdapter) {
                searchAdapter.setNewData(dataList);
                setResultListShow(searchAdapter.getData().size() > 0);
            } else {
                setResultListShow(false);
            }
        }
    }

    /**
     * 显示dialog
     *
     * @param activity   当前activity对象
     * @param searchView 搜索按钮  dialog显示时隐藏
     */
    public void showSearchDialog(final Activity activity, ViewGroup searchView) {
        this.searchView = searchView;
        if (null == activity) {
            return;
        }
        //隐藏搜索入口
        searchView.setVisibility(View.GONE);
        //初始化搜素监听
        myInputQueryListener = new MyInputQueryListener();

        //对当前的activity弱引用
        this.mActivity = (LocationSourceActivity) activity;
        //加载dialog布局
        View rootView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_location_search, null);
        dialog = LocationSearchDialogUtils.getBottomDialog(activity, rootView);
        //搜索框
        et_dialog_search = (EditText) rootView.findViewById(R.id.et_dialog_search);
        //清除按钮
        iv_dialog_del = (ImageView) rootView.findViewById(R.id.iv_dialog_del);
        //取消按钮
        tv_dialog_cancle = (TextView) rootView.findViewById(R.id.tv_dialog_cancle);
        //无数据背景
        view_search_bg = rootView.findViewById(R.id.view_search_bg);
        //搜索结果展示列表
        ll_search_result = (LinearLayout) rootView.findViewById(R.id.ll_search_result);
        rv_search_result = (RecyclerView) rootView.findViewById(R.id.rv_search_result);
        //设置recyler属性
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(dialog.getContext(), LinearLayout.VERTICAL, false);
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        rv_search_result.setLayoutManager(linearLayoutManager);
        rv_search_result.setItemAnimator(defaultItemAnimator);

        //输入框获取焦点
        et_dialog_search.setFocusable(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                ((LocationSourceActivity) activity).hideLoadView();
            }
        });
        showKeyBoard();

        //初始化搜索结果展示适配器
        searchAdapter = new LocationSearchAdapter(R.layout.adapter_location_search, dataList);
        rv_search_result.setAdapter(searchAdapter);

        initEdit();
        initClick();

        dialog.show();

    }

    /**
     * 初始化EditText, 设置监听
     */
    private void initEdit() {
        //输入框输入监听
        et_dialog_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //删除按钮显示
                iv_dialog_del.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString().trim();
                mActivity.showLoadView();
                if (!TextUtils.isEmpty(text)) {
                    setSearch(text);
                }
            }
        });
        //搜索按钮点击监听
        et_dialog_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    mActivity.showLoadView();
                    String input = et_dialog_search.getText().toString().trim();
                    setSearch(input);
                    return true;
                }
                return false;
            }
        });
        //dialog消失监听
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                searchView.setVisibility(View.VISIBLE);
                hideKeyBoard();
            }
        });
        /**
         * recylerView 条目点击
         */
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Message msg = new Message();
                msg.what = LocationHandlerKey.SEARCH;
                msg.obj = adapter.getData().get(position);
                mActivity.getLocationHandler().sendMessage(msg);
                //隐藏dialog
                dialog.dismiss();
                mActivity.hideLoadView();
            }
        });
    }

    /**
     * 按钮点击
     */
    private void initClick() {
        //清除按钮
        iv_dialog_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_dialog_search.setText("");
                setResultListShow(false);
                mActivity.hideLoadView();
            }
        });

        //取消按钮
        tv_dialog_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 显示软键盘 延时一定时间防止与EditText焦点冲突
     */
    private void showKeyBoard() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 180);

    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_dialog_search.getWindowToken(), 0);
    }

    /**
     * 搜索
     *
     * @param text 输入内容
     */
    private void setSearch(String text) {
        InputtipsQuery inputQuery = new InputtipsQuery(text, "");
        //限制在当前城市
        inputQuery.setCityLimit(false);
        Inputtips inputTips = new Inputtips(dialog.getContext(), inputQuery);
        inputTips.setInputtipsListener(myInputQueryListener);
        inputTips.requestInputtipsAsyn();
    }


    /**
     * 页面展示逻辑
     */
    private void setResultListShow(boolean isListShow) {
        if (isListShow) {
            view_search_bg.setVisibility(View.GONE);
            ll_search_result.setVisibility(View.VISIBLE);
        } else {
            view_search_bg.setVisibility(View.VISIBLE);
            ll_search_result.setVisibility(View.GONE);
        }
    }
}
